package com.zhz.mall.portal.modules.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhz.mall.common.api.ResultCode;
import com.zhz.mall.common.exception.Asserts;
import com.zhz.mall.portal.dto.AddCarDTO;
import com.zhz.mall.portal.dto.CartItemStockDTO;
import com.zhz.mall.portal.dto.CartUpdateQuantityDTO;
import com.zhz.mall.portal.modules.oms.mapper.OmsCartItemMapper;
import com.zhz.mall.portal.modules.oms.model.OmsCartItem;
import com.zhz.mall.portal.modules.oms.service.OmsCartItemService;
import com.zhz.mall.portal.modules.pms.model.PmsProduct;
import com.zhz.mall.portal.modules.pms.model.PmsSkuStock;
import com.zhz.mall.portal.modules.pms.service.PmsProductService;
import com.zhz.mall.portal.modules.pms.service.PmsSkuStockService;
import com.zhz.mall.portal.modules.ums.model.UmsMember;
import com.zhz.mall.portal.modules.ums.service.UmsMemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author zhouhengzhe
 * @since 2023-02-04
 */
@Service
public class OmsCartItemServiceImpl extends ServiceImpl<OmsCartItemMapper, OmsCartItem> implements OmsCartItemService {


    @Autowired
    private UmsMemberService umsMemberService;
    @Autowired
    private PmsSkuStockService pmsSkuStockService;
    @Autowired
    private PmsProductService pmsProductService;
    @Autowired
    private OmsCartItemMapper omsCartItemMapper;


    @Override
    public Boolean add(AddCarDTO addCarDTO) {
        OmsCartItem omsCartItem = new OmsCartItem();
        BeanUtils.copyProperties(addCarDTO, omsCartItem);
        UmsMember currentMember = umsMemberService.getCurrentMember();
        omsCartItem.setMemberId(currentMember.getId());
        //判断同一个商品、SKU、用户下是否添加的重复的购物车
        OmsCartItem cartItem = getCartItem(omsCartItem);
        //新增
        if (Objects.isNull(cartItem)) {
            return insertCartItem(omsCartItem, currentMember);
        }
        return updateCartItem(cartItem);
    }

    /**
     * 更新购物车项
     *
     * @param cartItem
     * @return
     */
    private boolean updateCartItem(OmsCartItem cartItem) {
        cartItem.setQuantity(cartItem.getQuantity() + 1);
        cartItem.setModifyDate(new Date());
        UpdateWrapper<OmsCartItem> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(OmsCartItem::getQuantity, cartItem.getQuantity())
                .set(OmsCartItem::getModifyDate, cartItem.getModifyDate())
                .eq(OmsCartItem::getId, cartItem.getId());
        return baseMapper.update(cartItem, updateWrapper) > 0;
    }

    private boolean insertCartItem(OmsCartItem omsCartItem, UmsMember currentMember) {
        omsCartItem.setMemberNickname(currentMember.getNickname());
        // 查询sku
        PmsSkuStock sku = pmsSkuStockService.getById(omsCartItem.getProductSkuId());
        if (sku == null) Asserts.fail(ResultCode.VALIDATE_FAILED);
        omsCartItem.setPrice(sku.getPrice());
        omsCartItem.setSp1(sku.getSp1());
        omsCartItem.setSp2(sku.getSp2());
        omsCartItem.setSp3(sku.getSp3());
        omsCartItem.setProductPic(sku.getPic());
        omsCartItem.setProductSkuCode(sku.getSkuCode());
        //获取商品信息
        PmsProduct product = pmsProductService.getById(omsCartItem.getProductId());
        if (Objects.isNull(product)) {
            Asserts.fail(ResultCode.VALIDATE_FAILED);
        }
        omsCartItem.setProductName(product.getName());
        omsCartItem.setProductBrand(product.getBrandName());
        omsCartItem.setProductSn(product.getProductSn());
        omsCartItem.setProductSubTitle(product.getSubTitle());
        omsCartItem.setProductCategoryId(product.getProductCategoryId());
        omsCartItem.setCreateDate(new Date());
        omsCartItem.setModifyDate(new Date());
        return baseMapper.insert(omsCartItem) > 0;
    }

    /**
     * 获取同一个商品、SKU、用户下是否添加的重复的购物车
     *
     * @param omsCartItem
     * @return
     */
    private OmsCartItem getCartItem(OmsCartItem omsCartItem) {
        QueryWrapper<OmsCartItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(OmsCartItem::getProductId, omsCartItem.getProductId())
                .eq(OmsCartItem::getProductSkuId, omsCartItem.getProductSkuId())
                .eq(OmsCartItem::getMemberId, omsCartItem.getMemberId());
        return this.baseMapper.selectOne(queryWrapper);
    }

    /**
     * 获取购物车商品数量
     *
     * @return
     */
    @Override
    public Integer getCartProductSum() {
        QueryWrapper<OmsCartItem> queryWrapper = new QueryWrapper<>();
        Long memberId = umsMemberService.getCurrentMember().getId();
        // 查询当前用户的购物车商品的数量  1个字段
        queryWrapper.select("sum(quantity) as total")
                .lambda()
                .eq(OmsCartItem::getMemberId, memberId);
        List<Map<String, Object>> list = baseMapper.selectMaps(queryWrapper);
        if (!CollectionUtils.isEmpty(list) && list.size() == 1) {
            Map<String, Object> map = list.get(0);
            if (Objects.nonNull(map.get("total"))) {
                return Integer.parseInt(map.get("total").toString());
            }
        }
        return 0;
    }

    /**
     * 获取购物数据初始化
     *
     * @return
     */
    @Override
    public List<CartItemStockDTO> getCartList() {
        // 1 当前用户
        UmsMember currentMember = umsMemberService.getCurrentMember();
        //获取当前用户的购物车信息
        return omsCartItemMapper.getCartItemStock(currentMember.getId());
    }

    /**
     * 更新商品数量
     *
     * @return
     */
    @Override
    public Boolean updateQuantity(CartUpdateQuantityDTO cartUpdateQuantityDTO) {
        UpdateWrapper<OmsCartItem> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(OmsCartItem::getQuantity, cartUpdateQuantityDTO.getQuantity())
                .eq(OmsCartItem::getId, cartUpdateQuantityDTO.getId());
        return this.update(updateWrapper);
    }

    /**
     * 删除购物车项
     *
     * @param ids
     * @return
     */
    @Override
    public Boolean delete(Long ids) {
        return this.removeById(ids);
    }

}
